/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.engine.cmd.application;

import cn.easyplatform.contexts.RecordContext;
import cn.easyplatform.dao.EntityCallback;
import cn.easyplatform.dao.IdentityDao;
import cn.easyplatform.dos.FieldDo;
import cn.easyplatform.entities.BaseEntity;
import cn.easyplatform.entities.beans.project.DeviceMapBean;
import cn.easyplatform.interceptor.AbstractCommand;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.lang.Times;
import cn.easyplatform.messages.request.SwitchOrgRequestMessage;
import cn.easyplatform.messages.response.SwitchOrgResponseMessage;
import cn.easyplatform.messages.vos.AgentVo;
import cn.easyplatform.messages.vos.RoleVo;
import cn.easyplatform.support.sql.SqlParser;
import cn.easyplatform.type.FieldType;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.util.EntityUtils;
import cn.easyplatform.util.RuntimeUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class SwitchOrgCmd extends AbstractCommand<SwitchOrgRequestMessage> {

    /**
     * @param req
     */
    public SwitchOrgCmd(SwitchOrgRequestMessage req) {
        super(req);
    }

    @Override
    public IResponseMessage<?> execute(final CommandContext cc) {
        IdentityDao dao = cc.getIdentityDao(false);
        String query = cc.getProjectService().getConfig().getUnitQuery();
        cc.getUser().setOrg(dao.getUserOrg(query, req.getBody()));
        cc.getUser()
                .getOrg()
                .setName(
                        RuntimeUtils.getLabel(cc, cc.getUser().getOrg()
                                .getName()));
        DeviceMapBean dm = cc.getProjectService().getDeviceMap(
                cc.getEnv().getPortlet(),
                cc.getEnv().getDeviceType().getName());
        SwitchOrgResponseMessage resp = new SwitchOrgResponseMessage(
                EntityUtils.parsePage(cc, dm.getMainPage()));
        if (cc.getProjectService().getConfig().getStrictMode() > 0) {
            EntityCallback<BaseEntity> cb = new EntityCallback<BaseEntity>() {
                @Override
                public BaseEntity getEntity(String entityId) {
                    return cc.getEntity(entityId);
                }

                public String getLabel(String code) {
                    return RuntimeUtils.getLabel(cc, code);
                }
            };
            List<RoleVo> roles = null;
            if (cc.getProjectService().getConfig().getStrictMode() == 1) {
                roles = dao.getUserRoles(
                        cc.getUser().getOrg().getId(), cc.getUser().getId(), cc
                                .getEnv().getDeviceType().getName(), cb);
            } else {
                List<RoleVo> ars = dao.getUserOrgRoles(cc.getUser().getOrg().getId(), cc.getUser().getId(), cc.getEnv().getDeviceType().getName(), cb);
                if (!ars.isEmpty())
                    roles = ars;
            }
            if (roles != null) {
                resp.setRoles(roles);
                cc.getUser().setRoles(roles);
            }
        }
        query = cc.getProjectService().getConfig()
                .getUserAgentRoleQuery();
        if (!Strings.isBlank(query)) {
            EntityCallback<BaseEntity> cb = new EntityCallback<BaseEntity>() {
                @Override
                public BaseEntity getEntity(String entityId) {
                    return cc.getEntity(entityId);
                }

                public String getLabel(String code) {
                    return RuntimeUtils.getLabel(cc, code);
                }
            };
            List<AgentVo> agents = new ArrayList<AgentVo>();
            Map<String, Object> systemVariables = new HashMap<String, Object>();
            Map<String, FieldDo> userVariables = new HashMap<String, FieldDo>();
            if (cc.getUser().getExtraInfo() != null)
                systemVariables.putAll(cc.getUser().getExtraInfo());
            if (cc.getUser().getOrg().getExtraInfo() != null)
                systemVariables.putAll(cc.getUser().getOrg().getExtraInfo());
            systemVariables.put("710", cc.getEnv().getPortlet());
            systemVariables.put("720", cc.getUser().getId());
            systemVariables.put("722", cc.getUser().getOrg().getId());
            systemVariables.put("728", cc.getEnv().getDeviceType()
                    .getName());
            RecordContext rc = new RecordContext(null, systemVariables,
                    userVariables);
            rc.setVariable(new FieldDo("dt", FieldType.DATE, Times.toDay()));
            SqlParser<FieldDo> parser = RuntimeUtils.createSqlParser(FieldDo.class);
            query = parser.parse(query, rc);
            List<String[]> users = dao.getAgent(query, parser.getParams());
            for (String[] user : users) {
                query = cc.getProjectService().getConfig()
                        .getUserAgentRoleQuery();
                if (Strings.isBlank(query)) {// 如果是空的，查找用户所有的角色
                    if (cc.getProjectService().getConfig().getStrictMode() == 1) {
                        agents.add(new AgentVo(user[0], user[1], dao
                                .getUserRoles(cc.getUser().getOrg().getId(), user[0], cc.getEnv()
                                        .getDeviceType().getName(), cb)));
                    } else {
                        List<RoleVo> ars = null;
                        if (cc.getProjectService().getConfig().getStrictMode() == 2) {
                            ars = dao.getUserOrgRoles(cc.getUser().getOrg().getId(), user[0], cc.getEnv()
                                    .getDeviceType().getName(), cb);
                        }
                        if (ars == null || ars.isEmpty())
                            ars = dao
                                    .getUserRoles(user[0], cc.getEnv()
                                            .getDeviceType().getName(), cb);
                        agents.add(new AgentVo(user[0], user[1], ars));
                    }
                } else {// 只查找设定的角色
                    systemVariables.put("720", user[0]);
                    parser = RuntimeUtils.createSqlParser(FieldDo.class);
                    query = parser.parse(query, rc);
                    List<RoleVo> agentRoles = dao.getRole(query,
                            parser.getParams(), cb);
                    for (RoleVo rv : agentRoles)
                        rv.setMenus(dao.getRoleMenu(rv.getId(), cc
                                .getEnv().getDeviceType().getName(), cb));
                    agents.add(new AgentVo(user[0], user[1], agentRoles));
                }
            }
            resp.setAgents(agents);
        }
        if (cc.getEngineConfiguration().getCacheManager().isCluster())
            cc.set(CommandContext.USER_KEY, cc.getUser());
        return resp;
    }
}
